import React, { useState, useCallback, useEffect } from 'react';
import './App.css';

import SubtitleDisplay from './components/SubtitleDisplay';
import FileImport from './components/FileImport';
import FileList from './components/FileList';
import BottomControls from './components/BottomControls';
import AISettings from './components/AISettings';
import TranslationProgress from './components/TranslationProgress';
import StorageManager from './components/StorageManager';

import { parseSRT, readFileAsText, matchAudioWithSubtitle } from './utils/srtParser';
import aiService from './utils/aiService';
import dbStorage from './utils/dbStorage';

function App() {
  const [filePairs, setFilePairs] = useState([]);
  const [selectedPair, setSelectedPair] = useState(null);
  const [subtitles, setSubtitles] = useState([]);
  const [audioUrl, setAudioUrl] = useState('');
  
  // 播放状态
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [playbackRate, setPlaybackRate] = useState(1);
  
  // 重复播放
  const [isRepeating, setIsRepeating] = useState(false);
  const [repeatStart, setRepeatStart] = useState(null);
  const [repeatEnd, setRepeatEnd] = useState(null);

  // AI功能状态
  const [aiConfig, setAiConfig] = useState({ enabled: false });
  const [showAISettings, setShowAISettings] = useState(false);
  const [showStorageManager, setShowStorageManager] = useState(false);
  const [showTranslation, setShowTranslation] = useState(false);
  const [isTranslating, setIsTranslating] = useState(false);
  const [translationProgress, setTranslationProgress] = useState({ current: 0, total: 0, text: '' });
  
  // 缓存恢复状态
  const [hasCachedFiles, setHasCachedFiles] = useState(false);
  const [isRestoring, setIsRestoring] = useState(false);

  // 初始化AI配置
  useEffect(() => {
    const savedConfig = localStorage.getItem('ai-settings');
    if (savedConfig) {
      try {
        const config = JSON.parse(savedConfig);
        setAiConfig(config);
        aiService.updateConfig(config);
      } catch (error) {
        console.error('Failed to load AI settings:', error);
      }
    }
  }, []);

  // 初始化数据库和清理过期缓存
  useEffect(() => {
    const initDB = async () => {
      try {
        await dbStorage.init();
        await dbStorage.cleanExpiredData();
        await checkCachedFiles();
      } catch (error) {
        console.error('初始化数据库失败:', error);
      }
    };
    
    initDB();
    aiService.clearExpiredCache();
  }, []);

  // 播放/暂停切换函数
  const handlePlayPause = useCallback(() => {
    setIsPlaying(!isPlaying);
  }, [isPlaying]);

  // 添加键盘快捷键监听
  useEffect(() => {
    const handleKeyDown = (event) => {
      // 检查是否在输入框中，如果是则不触发快捷键
      const activeElement = document.activeElement;
      const isInputActive = activeElement && (
        activeElement.tagName === 'INPUT' || 
        activeElement.tagName === 'TEXTAREA' || 
        activeElement.contentEditable === 'true'
      );
      
      // 如果正在输入或者没有选中音频文件，则不处理空格键
      if (isInputActive || !selectedPair) {
        return;
      }
      
      // 空格键播放/暂停
      if (event.code === 'Space') {
        event.preventDefault(); // 防止页面滚动
        handlePlayPause();
      }
    };

    // 添加事件监听
    document.addEventListener('keydown', handleKeyDown);

    // 清理事件监听
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [selectedPair, handlePlayPause]); // 依赖selectedPair和handlePlayPause函数

  // 检查是否有缓存文件
  const checkCachedFiles = async () => {
    try {
      const savedPairs = await dbStorage.getAppState('selectedFilePairs');
      if (savedPairs && savedPairs.length > 0) {
        setHasCachedFiles(true);
        console.log(`发现 ${savedPairs.length} 个缓存文件`);
      }
    } catch (error) {
      console.error('检查缓存文件失败:', error);
    }
  };

  // 手动恢复缓存文件
  const handleRestoreFromCache = async () => {
    if (isRestoring) return;
    
    setIsRestoring(true);
    try {
      await restoreAppState();
      setHasCachedFiles(false); // 恢复后隐藏按钮
    } catch (error) {
      console.error('手动恢复失败:', error);
      alert('恢复失败，请重新选择文件');
    } finally {
      setIsRestoring(false);
    }
  };

  // 恢复应用状态
  const restoreAppState = async () => {
    try {
      const savedPairs = await dbStorage.getAppState('selectedFilePairs');
      const savedCurrentPair = await dbStorage.getAppState('currentSelectedPair');
      
      if (savedPairs && savedPairs.length > 0) {
        const restoredPairs = [];
        
        for (const pairInfo of savedPairs) {
          try {
            // 尝试从IndexedDB恢复文件
            const audioData = await dbStorage.getFile(pairInfo.audioId);
            const subtitleData = pairInfo.subtitleId ? await dbStorage.getFile(pairInfo.subtitleId) : null;
            
            if (audioData) {
              // 验证数据完整性
              if (!audioData.content || !(audioData.content instanceof ArrayBuffer)) {
                throw new Error(`Invalid audio data: ${typeof audioData.content}`);
              }
              
              // Safari兼容的File对象创建
              let audioFile;
              try {
                // 检测Safari
                const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
                
                if (isSafari) {
                  // Safari兼容方式：先创建Blob，再创建File
                  const audioBlob = new Blob([audioData.content], { type: 'audio/mpeg' });
                  audioFile = new File([audioBlob], audioData.name, { type: 'audio/mpeg' });
                } else {
                  // 标准方式
                  audioFile = new File([audioData.content], audioData.name, {
                    type: 'audio/mpeg',
                    lastModified: audioData.lastModified
                  });
                }
              } catch (fileError) {
                console.error('File constructor failed, using Blob fallback:', fileError);
                // 最终fallback：创建一个带name属性的Blob
                const audioBlob = new Blob([audioData.content], { type: 'audio/mpeg' });
                audioBlob.name = audioData.name;
                audioFile = audioBlob;
              }
              
              let subtitleFile = null;
              if (subtitleData && subtitleData.content) {
                try {
                  const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
                  
                  if (isSafari) {
                    const subtitleBlob = new Blob([subtitleData.content], { type: 'text/plain' });
                    subtitleFile = new File([subtitleBlob], subtitleData.name, { type: 'text/plain' });
                  } else {
                    subtitleFile = new File([subtitleData.content], subtitleData.name, {
                      type: 'text/plain',
                      lastModified: subtitleData.lastModified
                    });
                  }
                } catch (subtitleError) {
                  console.error('Subtitle file creation failed:', subtitleError);
                  const subtitleBlob = new Blob([subtitleData.content], { type: 'text/plain' });
                  subtitleBlob.name = subtitleData.name;
                  subtitleFile = subtitleBlob;
                }
              }
              
              restoredPairs.push({
                audio: audioFile,
                subtitle: subtitleFile,
                audioId: pairInfo.audioId,
                subtitleId: pairInfo.subtitleId,
                confidence: pairInfo.confidence
              });
              
              console.log(`文件恢复成功: ${audioData.name}`, {
                browser: navigator.userAgent.includes('Safari') ? 'Safari' : 'Other',
                audioSize: audioData.content.byteLength,
                hasSubtitle: !!subtitleFile
              });
            }
          } catch (error) {
            console.error('恢复文件失败:', {
              pairInfo,
              error: error.message,
              browser: navigator.userAgent,
              stack: error.stack
            });
          }
        }
        
        if (restoredPairs.length > 0) {
          setFilePairs(restoredPairs);
          
          // 恢复当前选中的文件
          if (savedCurrentPair) {
            const currentPair = restoredPairs.find(pair => 
              pair.audioId === savedCurrentPair.audioId
            );
            
            if (currentPair) {
              await handlePairSelect(currentPair, true); // true表示是恢复状态
            }
          }
        }
      }
    } catch (error) {
      console.error('恢复应用状态失败:', error);
    }
  };

  // 保存应用状态
  const saveAppState = async () => {
    try {
      if (filePairs.length > 0) {
        const pairInfos = filePairs.map(pair => ({
          audioId: pair.audioId,
          subtitleId: pair.subtitleId,
          confidence: pair.confidence
        }));
        
        await dbStorage.saveAppState('selectedFilePairs', pairInfos);
        
        if (selectedPair) {
          await dbStorage.saveAppState('currentSelectedPair', {
            audioId: selectedPair.audioId,
            subtitleId: selectedPair.subtitleId
          });
        }
      }
    } catch (error) {
      console.error('保存应用状态失败:', error);
    }
  };

  // 页面可见性变化时保存状态
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.hidden) {
        saveAppState();
        savePlaybackState();
      }
    };
    
    const handleBeforeUnload = () => {
      saveAppState();
      savePlaybackState();
    };
    
    document.addEventListener('visibilitychange', handleVisibilityChange);
    window.addEventListener('beforeunload', handleBeforeUnload);
    
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [filePairs, selectedPair, currentTime, playbackRate, isRepeating, repeatStart, repeatEnd, showTranslation]);

  // 保存播放状态
  const savePlaybackState = async () => {
    if (selectedPair && selectedPair.audioId) {
      try {
        await dbStorage.savePlaybackState(selectedPair.audioId, {
          currentTime,
          playbackRate,
          isRepeating,
          repeatStart,
          repeatEnd,
          showTranslation
        });
      } catch (error) {
        console.error('保存播放状态失败:', error);
      }
    }
  };

  // 恢复播放状态
  const restorePlaybackState = async (audioId) => {
    try {
      const savedState = await dbStorage.getPlaybackState(audioId);
      if (savedState) {
        setCurrentTime(savedState.currentTime || 0);
        setPlaybackRate(savedState.playbackRate || 1);
        setIsRepeating(savedState.isRepeating || false);
        setRepeatStart(savedState.repeatStart || null);
        setRepeatEnd(savedState.repeatEnd || null);
        setShowTranslation(savedState.showTranslation || false);
      }
    } catch (error) {
      console.error('恢复播放状态失败:', error);
    }
  };

  const handleFilesSelect = useCallback(async ({ audioFiles, subtitleFiles }) => {
    const pairs = await matchAndCacheFiles(audioFiles, subtitleFiles);
    setFilePairs(prev => [...prev, ...pairs]);

    // 如果是第一对文件，自动选择
    if (filePairs.length === 0 && pairs.length > 0) {
      handlePairSelect(pairs[0]);
    }
  }, [filePairs.length]);

  // 匹配文件并缓存到IndexedDB
  const matchAndCacheFiles = async (audioFiles, subtitleFiles) => {
    const pairs = matchAudioWithSubtitle(audioFiles, subtitleFiles);
    const cachedPairs = [];

    for (const pair of pairs) {
      try {
        let audioId = null;
        let subtitleId = null;

        // 缓存音频文件
        if (pair.audio) {
          // 检查是否已经缓存
          const existingAudio = await dbStorage.findCachedFile(
            pair.audio.name,
            pair.audio.size,
            pair.audio.lastModified,
            'audio'
          );

          if (existingAudio) {
            audioId = existingAudio.id;
            console.log(`音频文件 ${pair.audio.name} 已存在缓存`);
          } else {
            // 读取文件内容并缓存
            const audioContent = await readFileAsArrayBuffer(pair.audio);
            audioId = await dbStorage.saveFile(pair.audio, audioContent, 'audio');
            console.log(`音频文件 ${pair.audio.name} 已缓存`);
          }
        }

        // 缓存字幕文件
        if (pair.subtitle) {
          const existingSubtitle = await dbStorage.findCachedFile(
            pair.subtitle.name,
            pair.subtitle.size,
            pair.subtitle.lastModified,
            'subtitle'
          );

          if (existingSubtitle) {
            subtitleId = existingSubtitle.id;
            console.log(`字幕文件 ${pair.subtitle.name} 已存在缓存`);
          } else {
            const subtitleContent = await readFileAsText(pair.subtitle);
            subtitleId = await dbStorage.saveFile(pair.subtitle, subtitleContent, 'subtitle');
            console.log(`字幕文件 ${pair.subtitle.name} 已缓存`);
          }
        }

        cachedPairs.push({
          ...pair,
          audioId,
          subtitleId
        });
      } catch (error) {
        console.error('缓存文件失败:', error);
        // 即使缓存失败，也添加到列表中
        cachedPairs.push(pair);
      }
    }

    return cachedPairs;
  };

  // 读取文件为ArrayBuffer
  const readFileAsArrayBuffer = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = () => reject(reader.error);
      reader.readAsArrayBuffer(file);
    });
  };

  const handlePairSelect = async (pair, isRestoring = false) => {
    setSelectedPair(pair);
    
    // 设置音频
    if (pair.audio) {
      try {
        // 验证音频对象
        if (!pair.audio || (!pair.audio.type && !pair.audio.name)) {
          throw new Error('Invalid audio file object');
        }
        
        const url = URL.createObjectURL(pair.audio);
        setAudioUrl(url);
        
        console.log(`音频URL创建成功: ${pair.audio.name}`, {
          type: pair.audio.type,
          size: pair.audio.size,
          isBlob: pair.audio instanceof Blob,
          isFile: pair.audio instanceof File
        });
      } catch (error) {
        console.error('创建音频URL失败:', error, pair.audio);
        // 清除可能的错误状态
        setAudioUrl('');
        alert('音频文件加载失败，请重新选择文件');
      }
    }
    
    // 解析字幕
    if (pair.subtitle) {
      try {
        const srtContent = await readFileAsText(pair.subtitle);
        const parsedSubtitles = parseSRT(srtContent);
        setSubtitles(parsedSubtitles);
      } catch (error) {
        console.error('Failed to parse subtitle:', error);
        setSubtitles([]);
      }
    } else {
      setSubtitles([]);
    }

    // 重置或恢复播放状态
    if (isRestoring && pair.audioId) {
      // 恢复模式：从数据库恢复播放状态
      await restorePlaybackState(pair.audioId);
    } else {
      // 正常模式：重置播放状态
      setIsPlaying(false);
      setCurrentTime(0);
      setIsRepeating(false);
      setRepeatStart(null);
      setRepeatEnd(null);
      setShowTranslation(false);
    }
    
    // 保存应用状态
    await saveAppState();
  };

  const handleRemovePair = (index) => {
    const newPairs = [...filePairs];
    const removedPair = newPairs.splice(index, 1)[0];
    
    // 如果移除的是当前选中的，清空选择
    if (selectedPair === removedPair) {
      setSelectedPair(null);
      setAudioUrl('');
      setSubtitles([]);
      setIsPlaying(false);
      setCurrentTime(0);
    }
    
    setFilePairs(newPairs);
    
    // 释放URL
    if (removedPair.audio) {
      URL.revokeObjectURL(audioUrl);
    }
  };

  const handleTimeUpdate = (time) => {
    setCurrentTime(time);
  };

  const handleSeek = (time) => {
    setCurrentTime(time);
  };

  const handleSubtitleClick = (startTime) => {
    setCurrentTime(startTime);
    setIsPlaying(true);
  };

  const handleRepeatToggle = () => {
    setIsRepeating(!isRepeating);
    if (!isRepeating) {
      // 如果没有设置重复范围，使用当前时间附近的字幕
      if (repeatStart === null || repeatEnd === null) {
        const currentSubtitle = subtitles.find(sub => 
          currentTime >= sub.start && currentTime <= sub.end
        );
        if (currentSubtitle) {
          setRepeatStart(currentSubtitle.start);
          setRepeatEnd(currentSubtitle.end);
        }
      }
    } else {
      setRepeatStart(null);
      setRepeatEnd(null);
    }
  };

  const handleRepeatSet = (start, end) => {
    setRepeatStart(start);
    setRepeatEnd(end);
    setIsRepeating(true);
    setCurrentTime(start);
    setIsPlaying(true);
  };

  // AI设置变化处理
  const handleAISettingsChange = (newConfig) => {
    setAiConfig(newConfig);
    aiService.updateConfig(newConfig);
  };

  // 翻译整个字幕
  const handleTranslateAll = async () => {
    if (!aiService.isEnabled() || !subtitles || subtitles.length === 0) {
      alert('请先配置AI设置并导入字幕文件');
      return;
    }

    setIsTranslating(true);
    setTranslationProgress({ current: 0, total: subtitles.length, text: '' });

    try {
      const translatedSubtitles = await aiService.translateAllSubtitles(
        subtitles,
        (current, total, currentText) => {
          setTranslationProgress({ current, total, text: currentText });
        }
      );

      setSubtitles(translatedSubtitles);
      setShowTranslation(true);
    } catch (error) {
      console.error('Translation failed:', error);
      alert('翻译失败：' + error.message);
    } finally {
      setIsTranslating(false);
    }
  };

  // 取消翻译
  const handleCancelTranslation = () => {
    setIsTranslating(false);
    // 这里可以添加取消翻译的逻辑
  };

  // 切换翻译显示
  const handleTranslationToggle = () => {
    if (!showTranslation && subtitles.length > 0 && !subtitles[0].translation) {
      // 如果没有翻译，先翻译
      handleTranslateAll();
    } else {
      setShowTranslation(!showTranslation);
    }
  };

  return (
    <div className="app">
      <header className="app-header">
        <div className="header-content">
          <div className="header-text">
            <h1>🎧 英语听力练习</h1>
            <p>支持MP3音频和SRT字幕文件同步播放</p>
          </div>
          <div className="header-actions">
            {hasCachedFiles && (
              <button 
                className="restore-cache-btn"
                onClick={handleRestoreFromCache}
                disabled={isRestoring}
                title="从缓存恢复之前的文件"
              >
                {isRestoring ? '⏳ 恢复中' : '🔄 恢复缓存'}
              </button>
            )}
            <button 
              className="ai-settings-btn"
              onClick={() => setShowAISettings(true)}
              title="AI翻译设置"
            >
              ⚙️ AI设置
            </button>
            <button 
              className="storage-manager-btn"
              onClick={() => setShowStorageManager(true)}
              title="缓存管理"
            >
              📦 缓存
            </button>
            {aiService.isEnabled() && selectedPair && subtitles.length > 0 && (
              <button 
                className="translate-all-btn"
                onClick={handleTranslateAll}
                disabled={isTranslating}
                title="一键翻译所有字幕"
              >
                {isTranslating ? '⏳ 翻译中' : '🌐 翻译'}
              </button>
            )}
          </div>
        </div>
      </header>

      <main className="app-main">
        {filePairs.length === 0 ? (
          <FileImport onFilesSelect={handleFilesSelect} />
        ) : (
          <>
            <FileList 
              filePairs={filePairs}
              selectedPair={selectedPair}
              onPairSelect={handlePairSelect}
              onRemovePair={handleRemovePair}
            />
            
            <FileImport onFilesSelect={handleFilesSelect} />
            
            {selectedPair && (
              <SubtitleDisplay
                subtitles={subtitles}
                currentTime={currentTime}
                onSubtitleClick={handleSubtitleClick}
                onRepeatSet={handleRepeatSet}
                showTranslation={showTranslation}
                onTranslationToggle={handleTranslationToggle}
                aiEnabled={aiService.isEnabled()}
              />
            )}
          </>
        )}
      </main>

      {/* 底部固定控制面板 */}
      {selectedPair && (
        <BottomControls
          audioSrc={audioUrl}
          currentTime={currentTime}
          onTimeUpdate={handleTimeUpdate}
          onSeek={handleSeek}
          playbackRate={playbackRate}
          onPlaybackRateChange={setPlaybackRate}
          isPlaying={isPlaying}
          onPlayPause={handlePlayPause}
          isRepeating={isRepeating}
          onRepeatToggle={handleRepeatToggle}
          repeatStart={repeatStart}
          repeatEnd={repeatEnd}
        />
      )}

      <footer className="app-footer">
        <p>© 2024 英语听力练习应用 - 让学习更高效</p>
      </footer>

      {/* AI设置弹窗 */}
      <AISettings
        isVisible={showAISettings}
        onClose={() => setShowAISettings(false)}
        onSettingsChange={handleAISettingsChange}
      />

      {/* 翻译进度弹窗 */}
      <TranslationProgress
        isVisible={isTranslating}
        progress={translationProgress.current}
        total={translationProgress.total}
        currentText={translationProgress.text}
        onCancel={handleCancelTranslation}
      />

      {/* 缓存管理弹窗 */}
      <StorageManager
        isVisible={showStorageManager}
        onClose={() => setShowStorageManager(false)}
      />
    </div>
  );
}

export default App;